package br.com.jmmarca.dao.generic;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import br.com.jmmarca.dao.impl.CorDAO;
import br.com.jmmarca.model.Cor;
import br.com.jmmarca.model.Evento;
import br.com.jmmarca.model.EventoProduto;
import br.com.jmmarca.model.Produto;
import br.com.jmmarca.model.ProdutoMidia;
import br.com.jmmarca.model.Usuario;
import br.com.jmmarca.model.Visitante;

public class OpenHelper extends SQLiteOpenHelper {
	
	protected Context context;

	public OpenHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		
		this.context = context;
		
	}

	@Override
	public void onOpen(SQLiteDatabase db) {
		super.onOpen(db);
		if (!db.isReadOnly()) {
			db.execSQL("PRAGMA foreign_keys=ON;");
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {

			new AbtractTableDefinition(Evento.class).onCreate(db);
			new AbtractTableDefinition(Produto.class).onCreate(db);
			new AbtractTableDefinition(EventoProduto.class).onCreate(db);
			new AbtractTableDefinition(Usuario.class).onCreate(db);
			new AbtractTableDefinition(Visitante.class).onCreate(db);
			new AbtractTableDefinition(ProdutoMidia.class).onCreate(db);
			new AbtractTableDefinition(Cor.class).onCreate(db);

			CorDAO corDAO = CorDAO.getInstance(context);
			Cor cor = new Cor();
			cor.setNome("Azul");
			cor.setCodigo("000000");
			corDAO.salvar(cor);
			cor.setNome("Vermelho");
			cor.setCodigo("000000");
			corDAO.salvar(cor);
			cor.setNome("Amarelo");
			cor.setCodigo("000000");
			corDAO.salvar(cor);
			cor.setNome("Verde");
			cor.setCodigo("000000");
			corDAO.salvar(cor);
			cor.setNome("Green");
			cor.setCodigo("000000");
			corDAO.salvar(cor);			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		try {		
			new AbtractTableDefinition(Evento.class).onUpgrade(db, oldVersion, newVersion);
			new AbtractTableDefinition(Produto.class).onUpgrade(db, oldVersion, newVersion);
			new AbtractTableDefinition(EventoProduto.class).onUpgrade(db, oldVersion, newVersion);
			new AbtractTableDefinition(Usuario.class).onUpgrade(db, oldVersion, newVersion);
			new AbtractTableDefinition(Visitante.class).onUpgrade(db, oldVersion, newVersion);
			new AbtractTableDefinition(ProdutoMidia.class).onUpgrade(db, oldVersion, newVersion);	
			new AbtractTableDefinition(Cor.class).onUpgrade(db, oldVersion, newVersion);		
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
